# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 用户管理
"""
import hashlib

from django.contrib.auth.hashers import make_password
from django.db import transaction
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.response import Response

from super.system.models import Users, Dept, Role
from super.utils.json_response import SuccessResponse, ErrorResponse
from super.utils.serializers import CustomModelSerializer
from super.utils.validator import CustomUniqueValidator
from super.utils.viewset import CustomModelViewSet
from django_restql.mixins import DynamicFieldsMixin


class UserSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """

    class Meta:
        model = Users
        read_only_fields = ["id"]
        exclude = ['password']
        extra_kwargs = {
            'post': {'required': False},
        }


class UserCreateSerializer(CustomModelSerializer):
    """
    用户新增-序列化器
    """
    username = serializers.CharField(max_length=50,
                                     validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
    password = serializers.CharField(required=False, default=make_password(
        hashlib.md5('admin123456'.encode(encoding='UTF-8')).hexdigest()))

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.post.set(self.initial_data.get('post', []))
        return data

    class Meta:
        model = Users
        fields = "__all__"
        read_only_fields = ["id"]
        extra_kwargs = {
            'post': {'required': False},
        }


class UserUpdateSerializer(CustomModelSerializer):
    """
    用户修改-序列化器
    """
    username = serializers.CharField(max_length=50,
                                     validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
    password = serializers.CharField(required=False, allow_blank=True)

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.post.set(self.initial_data.get('post', []))
        return data

    class Meta:
        model = Users
        read_only_fields = ["id"]
        fields = "__all__"
        extra_kwargs = {
            'post': {'required': False, 'read_only': True},
        }


from django_restql.mixins import QueryArgumentsMixin


class UserViewSet(QueryArgumentsMixin, CustomModelViewSet):
    """
    用户接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Users.objects.exclude(is_superuser=1).all()
    serializer_class = UserSerializer
    create_serializer_class = UserCreateSerializer
    update_serializer_class = UserUpdateSerializer
    filter_fields = ['name', 'username', 'gender', 'is_active', 'dept']
    # filter_fields = {
    #     'name': ['icontains'],
    #     'username': ['icontains'],
    #     'gender': ['icontains'],
    #     'is_active': ['icontains'],
    #     'dept': ['exact'],
    # }
    search_fields = ['username', 'name', 'gender', 'dept__name', 'role__name']

    @action(methods=['POST'], detail=False, permission_classes=[], extra_filter_backends=[], authentication_classes=[])
    def user_info(self, request):
        """获取当前用户信息"""
        user = request.user
        result = {
            "name": user.name,
            "mobile": user.mobile,
            "gender": user.gender,
            "email": user.email
        }
        return SuccessResponse(data=result, msg="获取成功")

    def update_user_info(self, request):
        """修改当前用户信息"""
        user = request.user
        Users.objects.filter(id=user.id).update(**request.data)
        return SuccessResponse(data=None, msg="修改成功")

    @action(methods=['POST'], detail=False, permission_classes=[], extra_filter_backends=[], authentication_classes=[])
    def username_is_valid(self, request):
        username = request.data.get('username')
        if self.queryset.filter(username=username).exists():
            return SuccessResponse({'username': username, 'is_exists': True}, is_page=False)
        else:
            return SuccessResponse({'username': username, 'is_exists': False}, is_page=False)

    @action(methods=['POST'], detail=False, permission_classes=[], extra_filter_backends=[], authentication_classes=[])
    def register(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        dep_name = request.data.get('depName')
        if not dep_name or not username or not password:
            raise ErrorResponse(msg='信息不完整')
        with transaction.atomic():
            # 创建部门
            dept = Dept(name=dep_name, sort=1)
            dept.save()
            # 创建用户
            user = Users(username=username, name=request.data.get('name'))
            user.set_password(password)
            user.dept = dept
            user.dept_belong_id = dept.id
            user.save()
            # 补充部门数据
            dept.dept_belong_id = dept.id
            dept.owner = user.username
            dept.creator = user
            dept.save()
            # 创建该用户权限
            role = Role.objects.get(key='public')
            user.role.add(role)
        return SuccessResponse({}, is_page=False)

    def change_password(self, request, *args, **kwargs):
        """密码修改"""
        instance = Users.objects.filter(id=kwargs.get('pk')).first()
        data = request.data
        old_pwd = data.get('oldPassword')
        new_pwd = data.get('newPassword')
        new_pwd2 = data.get('newPassword2')
        if instance:
            if new_pwd != new_pwd2:
                return ErrorResponse(msg="两次密码不匹配")
            elif instance.check_password(old_pwd):
                instance.password = make_password(new_pwd)
                instance.save()
                return SuccessResponse(data=None, msg="修改成功")
            else:
                return ErrorResponse(msg="旧密码不正确")
        else:
            return ErrorResponse(msg="未获取到用户")
